/*-----------------------------------------------------------------------------------
Name: Sangyoon Park
Date: January 24 2023
This do file does : 
	Create tables for main regression tables
-----------------------------------------------------------------------------------*/
clear all
set matsize 10000
set maxvar 10000
set more off
capture log close


#delim ;


/*-----------------------------------------------------------------------------------
			 Set up
-----------------------------------------------------------------------------------*/
*** Setting up files;
	glo datafile "qu_analysis"; 	// type in the name of the datafile that you want to create;

*** Set up program;
 ** Number Format;
	capture program drop autoformat;
	program define autoformat;

	if int(`1')==`1' global format "%12.0f";
	else if abs(`1')>10 global format "%9.1f";
	else if abs(`1')>1 global format "%9.2f";
	else if abs(`1')>.1 global format "%9.3f";
	else if abs(`1')>.01 global format "%9.3f";
	else if abs(`1')>.001 global format "%9.3f";
	else if abs(`1')>.0001 global format "%9.4f";
	else if abs(`1')<.00001 global format "%9.5f";

	end;
	
 ** Tex Table format;
  	capture program drop head_foot;
	program define head_foot;

	syntax, [caption(str)] [label(str)] [notes(str)] [size(str)] [columns(str)] [sideways] [long];

	local estimates=r(names);
	if "`columns'"=="" local columns:word count `estimates';
	if "`sideways'"=="sideways" local table sidewaystable;
	if "`long'"=="long" local table longtable;
	else local table table;
	local col = `columns'+1;

	global header \begin{`table'}[H] \footnotesize \begin{center};
		if "`size'"!="" global header $header \begin{`size'};
		if "`caption'"!="" global header $header \caption{`caption'\label{table:`label'}} ;
		global header $header  ///;
		\begin{adjustbox}{max width=\textwidth} ///;
		\begin{threeparttable} ///;
		\def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi} ;
		global header $header ///;
		\begin{tabular}{l*{`columns'}{c}}\toprule[1.5pt];

	global header_mid \tabularnewline;

	global panel_title \multicolumn{`col'}{l}{Panel}\tabularnewline \midrule;

	global footer_mid \midrule ;
	global footer \bottomrule[1.2pt] ///
		\end{tabular} ;
		if "`notes'"!="" {;
			global footer $footer \begin{tablenotes}[flushleft] ///;
			`notes' ///;
			\end{tablenotes} ;
			};
		global footer $footer \end{threeparttable}\end{adjustbox};
		if "`size'"!="" global footer $footer \end{`size'};
		global footer $footer \end{center} \end{`table'} 	;
	end;

*** table setting;
	local stat_balance cells("mean(fmt(2)) b(fmt(3) star)" "sd(par fmt(2)) t(par fmt(2))") ///;
			label noobs collabels(none) nonote ;
	local stat_table cells("mean(fmt(2))" "sd(par fmt(2))") label collabels(none) nonote ;

	local reg_table_format cells(b(fmt(3) star) se(par fmt(3))) star(* 0.10 ** 0.05 *** 0.01) ///;
		stats(N r2 ymean, fmt(0 3 2) labels("N" "R-Squared" "Mean of Dep. Var."))  ///;
		label mlabels(none) collabels(none) nonotes;

	local reg_table_format2 cells(b(fmt(3) star) se(par fmt(3))) star(* 0.10 ** 0.05 *** 0.01) ///;
		stats(ymean, fmt(3) labels("Mean of Dep. Var."))  ///;
		label mlabels(none) collabels(none) nonotes;

		
		
/*-----------------------------------------------------------------------------------
			 		DATA = GAME
-----------------------------------------------------------------------------------*/		

	import excel "${raw_path}/DATA_GAME_ALL.xlsx", sheet("Sheet1") firstrow ;
	tempfile game;
	save `game';
	clear;		
	
/*-----------------------------------------------------------------------------------
			 		DATA = EXPORTER SURVEY
-----------------------------------------------------------------------------------*/		

	use "${data_path}/INTERMEDIARY_LONG.dta", clear;
	rename age firmage;
		egen group_id = group(strata st_tgroup);
		gen tr_farm = (st_tgroup == 2 | st_tgroup == 6);
		gen tr_int = (st_tgroup == 3 | st_tgroup == 7);
		gen tr_joint = (st_tgroup == 4 | st_tgroup == 8);
		gen certelig = (st_tgroup == 5 | st_tgroup == 6 | st_tgroup == 7 | st_tgroup == 8);
		gen tr_fXcert = tr_farm * certelig;
		gen tr_iXcert = tr_int * certelig;
		gen tr_jXcert = tr_joint * certelig;	
	tempfile intdata;
	save `intdata';
	clear;	
	
/*-----------------------------------------------------------------------------------
			 		DATA = FARMER SURVEY
-----------------------------------------------------------------------------------*/		
	
*** Read data;
	
	use "${data_path}/FARMER_LONG_SETUP", replace;
	
*** Drop control communes;

	drop if control_commune == 1;	
	
*** Generate dummy for treatment groups;	
	
	tab st_tgroup, gen(dum_tgroup);

*** Cluster for standard errors;

	egen group_id = group(strata st_tgroup);

*** Generate treatment levels and interaction terms;

	gen tr_farm = (st_tgroup == 2 | st_tgroup == 6);
	gen tr_int = (st_tgroup == 3 | st_tgroup == 7);
	gen tr_joint = (st_tgroup == 4 | st_tgroup == 8);
	gen certelig = (st_tgroup == 5 | st_tgroup == 6 | st_tgroup == 7 | st_tgroup == 8);
	gen tr_fXcert = tr_farm * certelig;
	gen tr_iXcert = tr_int * certelig;
	gen tr_jXcert = tr_joint * certelig;
	gen control = (st_tgroup == 1 | st_tgroup == 5);
	

*** Drop large farms (farm size larger than five hectares);

	drop if ha_whitedragon >= 5;
	
*** Define local variables;
	
	local dummy_coef dum_tgroup2 dum_tgroup3 dum_tgroup4 dum_tgroup5 dum_tgroup6 dum_tgroup7 dum_tgroup8;
	local treat_coef tr_farm tr_int tr_joint certelig tr_fXcert tr_iXcert tr_jXcert;

	local baseline "age female edu_second exp_dragon ha_whitedragon tree_whitedragon anycert_base loan_any_base save_bank_base mean_trust_base mean_business_base mean_confidence_base raven_total present_bias_base gap_comply_base hours_base totalvolume_base price_base cost_fert_base cost_pest_base cost_facequip_base cost_labor_base cost_utility_base cost_total_base attrit_fu1 attrit_fu2";
	local balance age female edu_second exp_dragon ha_whitedragon white_age_less1 white_age_less3 white_age_less10 white_age_less20 white_age_more20 anycert_base loan_any_base save_bank_base mean_trust_base mean_business_base mean_confidence_base raven_total present_bias_base gap_comply_base hours_base totalvolume_base price_base log_cost_fert_base log_cost_pest_base log_cost_facequip_base log_cost_labor_base log_cost_utility_base;
	local intbalance int_age int_size_facility int_volume_china_fu0 int_volume_asia_fu0 int_volume_eu_fu0 int_volume_dom_fu0 int_dum_firmtype1 int_dum_firmtype2 int_dum_firmtype3;
	
/*-----------------------------------------------------------------------------------
			 		Label 
-----------------------------------------------------------------------------------*/
	lab var tr_farm "Farmer Training";
	lab var tr_int "Exporter Training";
	lab var tr_joint "Joint Training";
	lab var certelig "Certificate Eligibility (C.E.)";
	lab var tr_fXcert "C.E. $\times$ Farmer Training";
	lab var tr_iXcert "C.E. $\times$ Exporter Training";
	lab var tr_jXcert "C.E $\times$ Joint Training";
	lab var std_knowledge "Farmer GAP Knowledge";
	lab var std_perception "Farmer Food Safety Awareness";
	lab var int_std_knowledge "Exporter GAP Knowledge";
	lab var dist_nearest_treated "Distance to nearest jointly trained farmer (km)";
	lab var farmer_in2 "Number of farmers within 2km distance";
	lab var trader_in3 "Number of exporters within 3km distance";
	lab var trader_in2 "Number of exporters within 2km distance";
	lab var dist_jointtrader "Distance to nearest jointly trained exporter (km)";

	
tempfile maindata;
save `maindata';
clear;

	

	
/*-----------------------------------------------------------------------------------


			 		Tables for Main Text

					
-----------------------------------------------------------------------------------*/	


/*-----------------------------------------------------------------------------------
			 		OUTCOME = GAP Audit by Management Area (Table 2)
-----------------------------------------------------------------------------------*/	
use `maindata';

** Setting;
	loc titles "& Total & Pesticide & Equipment & Hygiene & Soil & Fertilizer \\ ";
	loc numbers "& (1) & (2) & (3) & (4) & (5) & (6) \\ \midrule";
	loc reg_table cells(b(fmt(3) star) se(par fmt(3))) starlevels(* 0.10 ** 0.05 *** 0.01) ///
		stats(betafi betafj betaij betafij ymean_control ysd_control r2 N, fmt(2 2 2 2 2 2 2 0) ///
		labels("P-value ($ \text{H}_0: \beta_{\text{farmer}} = \beta_{\text{int}}$)" "P-value ($ \text{H}_0: \beta_{\text{farmer}} = \beta_{\text{joint}}$)" "P-value ($ \text{H}_0: \beta_{\text{int}} = \beta_{\text{joint}}$)" "P-value ($ \text{H}_0: \beta_{\text{farmer}} + \beta_{\text{int}} = \beta_{\text{joint}}$)" "Control mean (Pass/Total)" "Control standard deviation" "R-squared" "Observations"))  ///
		label mlabels(none) collabels(none) nonotes nonumbers posthead("`titles'" "`numbers'") ///
		mgroups("Standardized scores from GAP audit" , pattern(1 0 0 0 0 0) ///
		span prefix(\multicolumn{@span}{c}{) suffix(}) erepeat(\cmidrule(lr){@span})) ///
		;

	local notes_gap \item Notes: Audit on GAP compliance was conducted in each of the two follow-up survey rounds. Audit scores are standardized by the control group's mean and standard deviation. ///
	Column 1 uses total audit score which is the number of items passed across all 32 items. ///
	Columns 2-6 use number of items passed in each management category. ///
	All specifications include farmer and intermediary characteristics at baseline as control variables as well as strata and survey round fixed effects. ///
	Standard errors are clustered by farmer group and reported in parentheses. P-values from randomization inference are reported in square brackets. * denotes false discovery rate controlled statistical significance at 0.10, ** at 0.05, and *** at 0.01.;		
		
		
** Estimation;
	local outcome "score pestman equipman hygman landman fertman";

		foreach y of local outcome {;
	
		eststo: qui reg std_`y' tr_farm tr_int tr_joint certelig tr_fXcert tr_iXcert tr_jXcert `balance' `intbalance' i.strata i.round, robust cluster(group_id);
		estadd ysumm;
		qui test tr_farm = tr_int;
		qui estadd scalar betafi = r(p);		
		qui test tr_farm = tr_joint;
		qui estadd scalar betafj = r(p);
		qui test tr_int = tr_joint;
		qui estadd scalar betaij = r(p);		
		qui test tr_farm+tr_int = tr_joint;
		qui estadd scalar betafij = r(p);
		qui sum audit_`y' if dum_tgroup1 == 1;
		qui estadd scalar ymean_control = r(mean);
		qui estadd scalar ysd_control = r(sd);
		};
		
** Table;
	loc colnum 6;
	local caption Impacts of Training and Certificate Eligibility on GAP Compliance;
	local label audit_result_pool;
	local notes `notes_gap';

head_foot, caption(`caption') label(`label') notes(`notes') columns(`colnum');

esttab  ///;
using "${table_path}/reg_audit_area_pool.tex", replace ///
	keep(tr_farm tr_int tr_joint certelig tr_fXcert tr_iXcert tr_jXcert) `reg_table' ///
	prehead("$header") postfoot("$footer") substitute("\_" "_");

est clear;





	
/*-----------------------------------------------------------------------------------
			 		OUTCOME = Pesticide Residue and Compliance (Table 3)
-----------------------------------------------------------------------------------*/


** Setting;
	loc titles1 " & Mean & \multicolumn{4}{c}{Compliance to country's MRL} \\ \cmidrule(lr){3-6} ";
	loc titles2 " & Residue & China & Japan & EU & US \\ \cmidrule(lr){2-6} ";	
	loc numbers "& (1) & (2) & (3) & (4) & (5) \\ \midrule";
	loc reg_table cells(b(fmt(3) star) se(par fmt(3))) starlevels(* 0.10 ** 0.05 *** 0.01) ///
		stats(betafi betafj betaij betafij ymean_control r2 N, fmt(2 2 2 2 2 2 0) ///
		labels("P-value ($ \text{H}_0: \beta_{\text{farmer}} = \beta_{\text{int}}$)" "P-value ($ \text{H}_0: \beta_{\text{farmer}} = \beta_{\text{joint}}$)" "P-value ($ \text{H}_0: \beta_{\text{int}} = \beta_{\text{joint}}$)" "P-value ($ \text{H}_0: \beta_{\text{farmer}} + \beta_{\text{int}} = \beta_{\text{joint}}$)" "Control mean" "R-squared" "Observations"))  ///
		label mlabels(none) collabels(none) nonotes nonumbers posthead("`titles1'" "`titles2'" "`numbers'") ///
		mgroups("Pesticide Residue Test", pattern(1 0 0 0) ///
		span prefix(\multicolumn{@span}{c}{) suffix(}) erepeat(\cmidrule(lr){@span})) ///
		;


	local notes_pesticide_eu \item Notes: Unit of observation is farmer. Outcome variable is constructed using pesticide test results from randomly sampled farmers. Column 1 scales residue levels by the pesticide's Maximum Residue Limit (MRL) according to EU and Columns 2-5 indicates compliance of all 18 pesticides to each country's MRL. ///
	All specifications include farmer and intermediary characteristics at baseline as control variables as well as strata fixed effects. ///
	Standard errors are clustered by farmer group and reported in parentheses. P-values from randomization inference are reported in square brackets. * denotes false discovery rate controlled statistical significance at 0.10, ** at 0.05, and *** at 0.01.;		
		
		
** Estimation;

	local outcome "mean_std_pest_eu comply_china comply_japan comply_eu comply_us";

		foreach y of local outcome {;
	
		eststo: qui reg `y' tr_farm tr_int tr_joint certelig tr_fXcert tr_iXcert tr_jXcert `balance' `intbalance' i.infogroup i.strata if round == 2, robust cluster(group_id);
		estadd ysumm;
		qui test tr_farm = tr_int;
		qui estadd scalar betafi = r(p);		
		qui test tr_farm = tr_joint;
		qui estadd scalar betafj = r(p);
		qui test tr_int = tr_joint;
		qui estadd scalar betaij = r(p);		
		qui test tr_farm+tr_int = tr_joint;
		qui estadd scalar betafij = r(p);		
		qui sum `y' if dum_tgroup1 == 1 & mean_std_pest_eu != .;
		qui estadd scalar ymean_control = r(mean);
		};
	
			
	
** Table;
	loc colnum 5;
	local caption Impact of Training and Certificate Eligibility on Pesticide Residue;
	local label pesticide_result;
	local notes `notes_pesticide_eu';

head_foot, caption(`caption') label(`label') notes(`notes') columns(`colnum');

esttab  ///;
using "${table_path}/reg_pesticide_residue_comply.tex", replace ///
	keep(tr_farm tr_int tr_joint certelig tr_fXcert tr_iXcert tr_jXcert) `reg_table' ///
	prehead("$header") postfoot("$footer") substitute("\_" "_");

est clear;


/*-----------------------------------------------------------------------------------
			 		OUTCOME = REVENUE AND PROFIT (Table 4, Online Appendix Table A-11)
-----------------------------------------------------------------------------------*/


** Setting;
	loc titles "& Price & Volume & Direct & Implied & Direct & Implied  \\ \cmidrule{2-7}";
	loc numbers "& (1) & (2) & (3) & (4) & (5) & (6)  \\ \midrule";
	loc reg_table cells(b(fmt(3) star) se(par fmt(3))) starlevels(* 0.10 ** 0.05 *** 0.01) ///
		stats(betafi betafj betaij betafij ymean_control r2 N, fmt(2 2 2 2 2 2 0) ///
		labels("P-value ($ \text{H}_0: \beta_{\text{farmer}} = \beta_{\text{int}}$)" "P-value ($ \text{H}_0: \beta_{\text{farmer}} = \beta_{\text{joint}}$)" "P-value ($ \text{H}_0: \beta_{\text{int}} = \beta_{\text{joint}}$)" "P-value ($ \text{H}_0: \beta_{\text{farmer}} + \beta_{\text{int}} = \beta_{\text{joint}}$)" "Control mean (in levels)" "R-squared" "Observations"))  ///
		label mlabels(none) collabels(none) nonotes nonumbers posthead("`titles'" "`numbers'") ///
		mgroups("Farm-gate" "Revenue" "Profit", pattern(1 0 1 0 1 0) ///
		span prefix(\multicolumn{@span}{c}{) suffix(}) erepeat(\cmidrule(lr){@span})) ///
		;
		
	local notes_sales \item Notes: This table reports treatment effects on farm sales. ///
	Sales data was collected from two follow-up survey rounds. Estimates are separately reported in each panel. Dependent variables in columns 1-4 are converted to log scales. Price is derived as the weighted-average of prices sold to intermediaries within each survey round where weights are the share of volume sold to each intermediary. /// 
	Direct revenue uses farmer reports on total revenue and Implied revenue is derived by aggregating revenues (product of price and volume) from each transaction reported in the survey. ///
	Direct Profit is derived by subtracting cost from direct revenue and Implied profit is calculated by subtracting cost from implied revenue. ///
	All specifications include farmer and intermediary characteristics at baseline as control variables as well as strata fixed effects. Standard errors are clustered by farmer group and reported in parentheses. ///
	P-values from randomization inference are reported in square brackets. * denotes false discovery rate controlled statistical significance at 0.10, ** at 0.05, and *** at 0.01.; 		
		
set seed 1357;
gen randnum = runiform();
drop if price == .;
drop if totalvolume == .;
drop if cost_costtotal == .;
drop if revenue == .;
		
forvalues i = 1(1)2 {;
** Estimation;
	local outcome "price totalvolume";

		foreach y of local outcome {;
		preserve;
		keep if round == `i';
		sort log_`y' randnum;
		drop if _n <= 10 | _n > _N-10;

	
		eststo: qui reg log_`y' tr_farm tr_int tr_joint certelig tr_fXcert tr_iXcert tr_jXcert `balance' `intbalance' i.strata if round == `i', robust cluster(group_id);
		estadd ysumm;
		qui test tr_farm = tr_int;
		qui estadd scalar betafi = r(p);		
		qui test tr_farm = tr_joint;
		qui estadd scalar betafj = r(p);
		qui test tr_int = tr_joint;
		qui estadd scalar betaij = r(p);		
		qui test tr_farm+tr_int = tr_joint;
		qui estadd scalar betafij = r(p);	
		qui sum `y' if dum_tgroup1 == 1 & round == `i';
		qui estadd scalar ymean_control = r(mean);
		restore;
		};
	
	
	local outcome "revenue imp_revenue profit imp_profit";

		foreach y of local outcome {;
		preserve;
		keep if round == `i';
		sort `y' randnum;
		drop if _n <= 10 | _n > _N-10;

	
		eststo: qui reg `y' tr_farm tr_int tr_joint certelig tr_fXcert tr_iXcert tr_jXcert `balance' `intbalance' i.strata if round == `i', robust cluster(group_id);
		estadd ysumm;
		qui test tr_farm = tr_int;
		qui estadd scalar betafi = r(p);		
		qui test tr_farm = tr_joint;
		qui estadd scalar betafj = r(p);
		qui test tr_int = tr_joint;
		qui estadd scalar betaij = r(p);		
		qui test tr_farm+tr_int = tr_joint;
		qui estadd scalar betafij = r(p);	
		qui sum `y' if dum_tgroup1 == 1 & round == `i';
		qui estadd scalar ymean_control = r(mean);
		restore;
		};		

** Table;
	loc colnum 6;
	local caption Impact of Training and Certificate Eligibility on Farm Sales - Round `i';
	local label farmsales_result_pool;
	local notes `notes_sales';

head_foot, caption(`caption') label(`label') notes(`notes') columns(`colnum');

esttab  ///;
using "${table_path}/reg_farmsales_nologprofit_round`i'.tex", replace ///
	keep(tr_farm tr_int tr_joint certelig tr_fXcert tr_iXcert tr_jXcert) `reg_table' ///
	prehead("$header") postfoot("$footer") substitute("\_" "_");
est clear;
	};


/*-----------------------------------------------------------------------------------
			 Trust and Dictator game outcomes (Table 5)
-----------------------------------------------------------------------------------*/

*** Append with Intermediary data;
	use `maindata', clear;
	append using `intdata';
	gen newid = farmerid if farmerid !=.;
	replace newid = traderid+20000 if traderid !=.;
	order newid;
	keep if round == 1;
	gen farmer = (farmerid!=.);


** Merge with game records;
	merge m:1 newid using `game';
	keep if _merge== 3;
	drop _merge;


** Generate variables;

gen g1_partner_int = (g1_partnernewid >= 20000 & g1_partnernewid !=.);
gen g2_partner_int = (g2_partnernewid >= 20000 & g2_partnernewid !=.);
gen g3_partner_int = (g3_partnernewid >= 20000 & g3_partnernewid !=.);	

gen g1_partnershare = g1_partner/100;
gen g2_partnershare = g2_partner/100;
gen g3_partnershare = g3_partner/150;

local outcome "g1_partner g2_partner g3_partner";
local treat_coef tr_farm tr_int tr_joint certelig tr_fXcert tr_iXcert tr_jXcert;

	foreach y of local outcome {;
	foreach x of local treat_coef {;
	gen `y'X`x' = `y'_int*`x';
	};
	};

local g1_partner_char g1_partner_age g1_partner_size g1_partner_volume g1_partner_score g1_partner_type;
local g2_partner_char g2_partner_age g2_partner_size g2_partner_volume g2_partner_score g2_partner_type;
local g3_partner_char g3_partner_age g3_partner_size g3_partner_volume g3_partner_score g3_partner_type;

local g1_treat_coef g1_partnerXtr_farm g1_partnerXtr_int g1_partnerXtr_joint g1_partnerXcertelig g1_partnerXtr_fXcert g1_partnerXtr_iXcert g1_partnerXtr_jXcert;		
local g2_treat_coef g2_partnerXtr_farm g2_partnerXtr_int g2_partnerXtr_joint g2_partnerXcertelig g2_partnerXtr_fXcert g2_partnerXtr_iXcert g2_partnerXtr_jXcert;		
local g3_treat_coef g3_partnerXtr_farm g3_partnerXtr_int g3_partnerXtr_joint g3_partnerXcertelig g3_partnerXtr_fXcert g3_partnerXtr_iXcert g3_partnerXtr_jXcert;		

	foreach x of local treat_coef {;
	gen partnerX`x' = .;
	};			

local partnerXcoef partnerXtr_farm partnerXtr_int partnerXtr_joint partnerXcertelig partnerXtr_fXcert partnerXtr_iXcert partnerXtr_jXcert;	
gen partner_int = .;

local costvar log_fert log_pest log_facility log_equip log_labor log_utility hours;

local treat_coef tr_farm tr_int tr_joint certelig tr_fXcert tr_iXcert tr_jXcert;

local int_balance "firmage dum_firmtype1 dum_firmtype2 dum_firmtype3 size_facility buy_avgprice_fu0 sell_avgprice_fu0 ghp_score_fu0 sell_contract_fu0 sell_exp_fu0 volume_china_fu0 volume_asia_fu0 volume_eu_fu0 volume_dom_fu0";
	
/*-----------------------------------------------------------------------------------
			 		Label 
-----------------------------------------------------------------------------------*/
	lab var tr_farm "Farmer Training";
	lab var tr_int "Exporter Training";
	lab var tr_joint "Joint Training";
	lab var certelig "Certificate Eligibility (C.E.)";
	lab var tr_fXcert "C.E. $\times$ Farmer Training";
	lab var tr_iXcert "C.E. $\times$ Exporter Training";
	lab var tr_jXcert "C.E. $\times$ Joint Training";

/*-----------------------------------------------------------------------------------
			 		Label 
-----------------------------------------------------------------------------------*/
	lab var partner_int "Partner is Exporter";
	lab var partnerXtr_farm " $\times$ Farmer Training";
	lab var partnerXtr_int " $\times$ Exporter Training";
	lab var partnerXtr_joint " $\times$ Joint Training";
	
	

** Setting;
	loc titles0 "& \multicolumn{2}{c}{1st stage} & \multicolumn{2}{c}{2nd stage} & \\ \cmidrule(lr){2-3} \cmidrule(lr){4-5}";
	loc titles1 "& Proportion & Proportion & Proportion & Proportion & Proportion & Proportion \\";
	loc titles2 "& farmer passed & exporter passed & farmer returned & exporter returned & farmer passed & exporter passed \\";
	loc titles3 "& to exporter & to farmer & to exporter & to farmer & to exporter & to farmer \\ \cmidrule(lr){2-7}";	

	loc numbers "& (1) & (2) & (3) & (4) & (5) & (6) \\ \midrule";
	loc reg_table cells(b(fmt(3) star) se(par fmt(3))) starlevels(* 0.10 ** 0.05 *** 0.01) ///
		stats(betafi betafj betaij betafij ymean_control r2 N, fmt(2 2 2 2 2 2 0) ///
		labels("P-value ($ \text{H}_0: \gamma_{\text{farmer}} = \gamma_{\text{int}}$)" "P-value ($ \text{H}_0: \gamma_{\text{farmer}} = \gamma_{\text{joint}}$)" "P-value ($ \text{H}_0: \gamma_{\text{int}} = \gamma_{\text{joint}}$)" "P-value ($ \text{H}_0: \gamma_{\text{farmer}} + \gamma_{\text{int}} = \gamma_{\text{joint}}$)" "Control mean" "R-squared" "Observations"))  ///
		label mlabels(none) collabels(none) nonotes nonumbers posthead("`titles0'" "`titles1'" "`titles2'" "`titles3'" "`numbers'") ///
		mgroups("Trust Game" "Dictator Game", pattern(1 0 0 0 1 0) ///
		span prefix(\multicolumn{@span}{c}{) suffix(}) erepeat(\cmidrule(lr){@span})) ///
		;


	local notes_trust \item Notes: This table reports treatment effects on outcomes of trust and dictator games. ///
	Column 1 is the share of money a farmer passed to his or her partner in the first stage of the trust game and 2 is the share of money a farmer returned to his or her partner in the second stage. Column 3 is the share of money passed to a partner in the dictator game. ///
	Specifications include farmer characteristics at baseline as control variables, indicators for certification eligibility and its interaction with training treatments, and strata fixed effects. ///
	Standard errors are clustered by farmer-intermediary cluster and reported in parentheses. * denotes statistical significance at 0.10, ** at 0.05, and *** at 0.01.; 
	
	local notes_trust_pool \item Notes: This table reports treatment effects on outcomes of trust and dictator games. ///
	Column 1 is the share of money a farmer or intermediary (Column 2) passed to his or her partner in the first stage of the trust game and 3 is the share of money a farmer or intermediary (Column 4) returned to his or her partner in the second stage. Column 5 is the share of money a farmer or intermediary (Column 6) passed to his or her partner in the dictator game. ///
	Specifications include farmer or intermediary (Columns 2,4,6) characteristics at baseline as control variables, indicators for certification eligibility and its interaction with training treatments, and strata fixed effects. ///
	Standard errors are clustered by farmer-intermediary cluster and reported in parentheses. * denotes statistical significance at 0.10, ** at 0.05, and *** at 0.01.; 		
	

 forvalues i = 1(1)3 {;
		gen g`i'_intergroup = (g`i'_partner_int == 1 & farmer == 1 | g`i'_partner_int == 0 & farmer == 0);
		gen g`i'_partner_intXfarm = g`i'_partner_int*tr_farm;
		gen g`i'_partner_intXinter = g`i'_partner_int*tr_int;
		gen g`i'_partner_intXjoint = g`i'_partner_int*tr_joint;
		
			};


		local outcome "g2 g3 g1";

		foreach y of local outcome {;

		preserve;
		keep if farmer == 1;

		eststo: reg `y'_partnershare `treat_coef' `balance' i.strata if `y'_partner_int == 1, robust cluster(group_id); 	
		estadd ysumm;
		qui test tr_farm = tr_int;
		qui estadd scalar betafi = r(p);		
		qui test tr_farm = tr_joint;
		qui estadd scalar betafj = r(p);
		qui test tr_int = tr_joint;
		qui estadd scalar betaij = r(p);		
		qui test tr_farm+tr_int = tr_joint;
		qui estadd scalar betafij = r(p);
		qui sum `y'_partnershare if st_tgroup == 1 & `y'_partner_int == 1;
		qui estadd scalar ymean_control = r(mean);
		
		restore;
		
		preserve;
		keep if farmer == 0;
	
		
			eststo: reg `y'_partnershare `treat_coef' `int_balance' i.strata if `y'_partner_int == 0, robust cluster(group_id); 	
		estadd ysumm;
		qui test tr_farm = tr_int;
		qui estadd scalar betafi = r(p);		
		qui test tr_farm = tr_joint;
		qui estadd scalar betafj = r(p);
		qui test tr_int = tr_joint;
		qui estadd scalar betaij = r(p);		
		qui test tr_farm+tr_int = tr_joint;
		qui estadd scalar betafij = r(p);
		qui sum `y'_partnershare if st_tgroup == 1 & `y'_partner_int == 0;
		qui estadd scalar ymean_control = r(mean);
		
		restore;
		
		
		};
		

	
** Table;
	loc colnum 6;
	local caption Treatment Effects on Behavior in Trust and Dictator Games;
	local label trust_result;
	local notes `notes_trust_pool';

head_foot, caption(`caption') label(`label') notes(`notes') columns(`colnum');

esttab  ///;
using "${table_path}/reg_trust_pool.tex", replace ///
	keep(tr_farm tr_int tr_joint certelig tr_fXcert tr_iXcert tr_jXcert) `reg_table' ///
	prehead("$header") postfoot("$footer") substitute("\_" "_");

est clear;
clear;	


/*-----------------------------------------------------------------------------------
			 		TRADE WITH INTERMEDIARIES
-----------------------------------------------------------------------------------*/		
/*-----------------------------------------------------------------------------------
			 		SALES TRANSACTION LEVEL ANALYSIS
-----------------------------------------------------------------------------------*/	

clear;
*** Read data;
	
	use "${data_path}/FARMER_COMBINETRADE_CLEAN", replace;

	rename followup round;

	merge m:1 farmerid round using "${data_path}/FARMER_LONG_SETUP";
	keep if _merge == 3;
	drop _merge;
	
*** Drop control communes;

	drop if control_commune == 1;	
	
*** Generate dummy for treatment groups;	
	
	tab st_tgroup, gen(dum_tgroup);
	
*** Cluster for standard errors;

	egen group_id = group(strata st_tgroup);

*** Drop large farms (farm size larger than five hectares);

	drop if ha_whitedragon >= 5;	
	
*** Generate treatment levels and interaction terms;

	gen tr_farm = (st_tgroup == 2 | st_tgroup == 6);
	gen tr_int = (st_tgroup == 3 | st_tgroup == 7);
	gen tr_joint = (st_tgroup == 4 | st_tgroup == 8);
	gen certelig = (st_tgroup == 5 | st_tgroup == 6 | st_tgroup == 7 | st_tgroup == 8);
	gen tr_fXcert = tr_farm * certelig;
	gen tr_iXcert = tr_int * certelig;
	gen tr_jXcert = tr_joint * certelig;
	gen iv_tr_farmer = (tr_farm == 1 | tr_joint == 1);
	gen control = (st_tgroup == 1 | st_tgroup == 5);
	
** Generate outcome variables;

	gen log_buyer_price = log(buyer_price);
	tab buyer_type, gen(dum_type);
	tab buyer_contract, gen(dum_contract);
	gen nonprogmeet = (1-progmeet);
	gen contract_within = (buyer_contract == 1 | buyer_contract == 2)*progmeet ;
	gen contract_outside = (buyer_contract == 1 | buyer_contract == 2)*nonprogmeet;
	gen spot_within = (buyer_contract == 3)*progmeet ;
	gen spot_outside = (buyer_contract == 3)*nonprogmeet ;
	replace contract_within = 0 if buyer_type == 1 ;
	replace contract_outside = 0 if buyer_type == 1 ;	
	replace spot_within = (buyer_type == 1)*progmeet ;
	replace spot_outside = (buyer_type == 1)*nonprogmeet ;
	
	local balance age female edu_second exp_dragon ha_whitedragon white_age_less1 white_age_less3 white_age_less10 white_age_less20 white_age_more20 anycert_base loan_any_base save_bank_base mean_trust_base mean_business_base mean_confidence_base raven_total present_bias_base gap_comply_base hours_base totalvolume_base price_base log_cost_fert_base log_cost_pest_base log_cost_facequip_base log_cost_labor_base log_cost_utility_base;
	local intbalance int_age int_size_facility int_volume_china_fu0 int_volume_asia_fu0 int_volume_eu_fu0 int_volume_dom_fu0 int_dum_firmtype1 int_dum_firmtype2 int_dum_firmtype3;
	
/*-----------------------------------------------------------------------------------
			 		Label 
-----------------------------------------------------------------------------------*/
	lab var age "Age";
	lab var female "Female";
	lab var edu_second "Secondary Education";
	lab var exp_dragon "Experience growing dragon fruit (years)";
	lab var ha_whitedragon "Size of dragon fruit farm (hectares)";
	lab var tree_whitedragon "Number of dragon fruit trees";
	lab var anycert_base "Received any agricultural certificate before";
	lab var loan_any_base "Ever received loan for farm investment";
	lab var save_bank_base "Ever saved at bank";
	lab var mean_trust_base "Mean score on trust measurement";
	lab var mean_business_base "Mean score on business measurement";
	lab var mean_confidence_base "Mean score on confidence measurement";
	lab var raven_total "Raven matrices score";
	lab var present_bias_base "Time discounting - present biased";
	lab var gap_comply_base "Self-reported GAP compliance";
	lab var dum_market1 "China";
	lab var dum_market2 "Asia (excluding China)";
	lab var dum_market3 "EU/US";
	lab var dum_market4 "Domestic";
	lab var std_score "GAP compliance";
	lab var std_sweet "Sweetness";
	lab var std_skin "Skin";
	lab var std_bract "Bract";
	lab var std_length "Length";
	lab var std_width "Width";
	lab var std_weight "Weight";
	lab var tr_farm "Farmer Training";
	lab var tr_int "Exporter Training";
	lab var tr_joint "Joint Training";
	lab var certelig "Certificate Eligibility (C.E.)";
	lab var tr_fXcert "C.E. $\times$ Farmer Training";
	lab var tr_iXcert "C.E. $\times$ Exporter Training";
	lab var tr_jXcert "C.E. $\times$ Joint Training";
	lab var sum_overmrl_eu "Residue $\geq$ E.U. Limit";
	lab var progmeet "Buyer was program participant";
	lab var dist_nearest_treated "Distance to nearest jointly trained farmer (km)";
	lab var farmer_in2 "Number of farmers within 2km distance";
	lab var trader_in3 "Number of exporters within 3km distance";
	lab var trader_in2 "Number of exporters within 2km distance";
	lab var dist_jointtrader "Distance to nearest jointly trained exporter (km)";	
	


/*-----------------------------------------------------------------------------------
			 		IMPACT ON TRADE WITH INTERMEDIARIES (Table 6)
-----------------------------------------------------------------------------------*/		
	
** Setting;
	loc titles1 "& Within & Within & Outside & Within & Outside \\ ";
	loc titles2 "& cluster & cluster & cluster & cluster & cluster \\ \cmidrule{2-6}";
	loc numbers "& (1) & (2) & (3) & (4) & (5)  \\ \midrule";
	loc reg_table cells(b(fmt(3) star) se(par fmt(3))) starlevels(* 0.10 ** 0.05 *** 0.01) ///
		stats(betafi betafj betaij betafij ymean_control r2 N, fmt(2 2 2 2 2 2 0) ///
		labels("P-value ($ \text{H}_0: \beta_{\text{farmer}} = \beta_{\text{int}}$)" "P-value ($ \text{H}_0: \beta_{\text{farmer}} = \beta_{\text{joint}}$)" "P-value ($ \text{H}_0: \beta_{\text{int}} = \beta_{\text{joint}}$)" "P-value ($ \text{H}_0: \beta_{\text{farmer}} + \beta_{\text{int}} = \beta_{\text{joint}}$)" "Control mean" "R-squared" "Observations"))  ///
		label mlabels(none) collabels(none) nonotes nonumbers posthead("`titles1'" "`titles2'" "`numbers'") ///
		mgroups("Any Trade" "Spot Trade" "Contract Trade", pattern(1 1 0 1 0) ///
		span prefix(\multicolumn{@span}{c}{) suffix(}) erepeat(\cmidrule(lr){@span})) ///
		;

	local notes_ols_contractintermediary \item Notes: This table reports treatment effects on contract trading between farmers and intermediaries. ///
	The results use farm-gate sales data from two follow-up survey rounds. The dependent variable in Column 1 indicates whether the farmer traded with intermediary from same training group. Columns 2-3 report coefficient estimates on ispot trade during the survey period. Columns 4-5 report estimates on informal or formal contract trade. Within cluster refers to trade with exporters in the same training cluster and Outside cluster refers to any intermediary, exporter or collector, not in the same training cluster. ///
	Standard errors are clustered by farmer group and reported in parentheses. ///
	All specifications include farmer and intermediary characteristics at baseline as control variables as well as strata and survey round fixed effects. * denotes false discovery rate controlled statistical significance at 0.10, ** at 0.05, and *** at 0.01.;
	


** Estimation;
		eststo: qui reg progmeet tr_farm tr_int tr_joint certelig tr_fXcert tr_iXcert tr_jXcert `balance' `intbalance' i.round i.strata, robust cluster(group_id);
			estadd ysumm;
		qui test tr_farm = tr_int;
		qui estadd scalar betafi = r(p);		
		qui test tr_farm = tr_joint;
		qui estadd scalar betafj = r(p);
		qui test tr_int = tr_joint;
		qui estadd scalar betaij = r(p);		
		qui test tr_farm+tr_int = tr_joint;
		qui estadd scalar betafij = r(p);	
			qui sum progmeet if dum_tgroup1 == 1;
			qui estadd scalar ymean_control = r(mean);
			estadd scalar pr2 = e(r2);	

		
		eststo: qui reg spot_within tr_farm tr_int tr_joint certelig tr_fXcert tr_iXcert tr_jXcert `balance' `intbalance' i.round i.strata, robust cluster(group_id);
			estadd ysumm;
		
		qui test tr_farm = tr_int;
		qui estadd scalar betafi = r(p);		
		qui test tr_farm = tr_joint;
		qui estadd scalar betafj = r(p);
		qui test tr_int = tr_joint;
		qui estadd scalar betaij = r(p);		
		qui test tr_farm+tr_int = tr_joint;
		qui estadd scalar betafij = r(p);	
			qui sum spot_within if dum_tgroup1 == 1;
			qui estadd scalar ymean_control = r(mean);
			estadd scalar pr2 = e(r2);


		eststo: qui reg spot_outside tr_farm tr_int tr_joint certelig tr_fXcert tr_iXcert tr_jXcert `balance' `intbalance' i.round i.strata, robust cluster(group_id);
			estadd ysumm;
		
		qui test tr_farm = tr_int;
		qui estadd scalar betafi = r(p);		
		qui test tr_farm = tr_joint;
		qui estadd scalar betafj = r(p);
		qui test tr_int = tr_joint;
		qui estadd scalar betaij = r(p);		
		qui test tr_farm+tr_int = tr_joint;
		qui estadd scalar betafij = r(p);	
			qui sum spot_outside if dum_tgroup1 == 1;
			qui estadd scalar ymean_control = r(mean);
			estadd scalar pr2 = e(r2);			

		eststo: qui reg contract_within tr_farm tr_int tr_joint certelig tr_fXcert tr_iXcert tr_jXcert `balance' `intbalance' i.round i.strata, robust cluster(group_id);
			estadd ysumm;
		
		qui test tr_farm = tr_int;
		qui estadd scalar betafi = r(p);		
		qui test tr_farm = tr_joint;
		qui estadd scalar betafj = r(p);
		qui test tr_int = tr_joint;
		qui estadd scalar betaij = r(p);		
		qui test tr_farm+tr_int = tr_joint;
		qui estadd scalar betafij = r(p);	
			qui sum contract_within if dum_tgroup1 == 1;
			qui estadd scalar ymean_control = r(mean);
			estadd scalar pr2 = e(r2);


		eststo: qui reg contract_outside tr_farm tr_int tr_joint certelig tr_fXcert tr_iXcert tr_jXcert `balance' `intbalance' i.round i.strata, robust cluster(group_id);
			estadd ysumm;
		
		qui test tr_farm = tr_int;
		qui estadd scalar betafi = r(p);		
		qui test tr_farm = tr_joint;
		qui estadd scalar betafj = r(p);
		qui test tr_int = tr_joint;
		qui estadd scalar betaij = r(p);		
		qui test tr_farm+tr_int = tr_joint;
		qui estadd scalar betafij = r(p);	
			qui sum contract_outside if dum_tgroup1 == 1;
			qui estadd scalar ymean_control = r(mean);
			estadd scalar pr2 = e(r2);			


** Table;
	loc colnum 5;
	local caption Impact of Training on Contract Trade;
	local label contractintermediary_result;
	local notes `notes_ols_contractintermediary';

head_foot, caption(`caption') label(`label') notes(`notes') columns(`colnum');

esttab  ///;
using "${table_path}/reg_contractintermediary.tex", replace ///
	keep(tr_farm tr_int tr_joint certelig tr_fXcert tr_iXcert tr_jXcert) `reg_table' ///
	prehead("$header") postfoot("$footer") substitute("\_" "_");

est clear;
		








	
	
	
	
	
	
	
	
	
	
	
	
	
	

	
